/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.rest.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.geoscheduler.android.GSContext;
import org.geoscheduler.android.exceptions.GSContextNotInitializedException;
import org.geoscheduler.android.exceptions.GSNotLoggedInException;
import org.geoscheduler.android.exceptions.GSRestFailedException;
import org.geoscheduler.android.exceptions.GSRestReturnedErrorException;
import org.geoscheduler.android.rest.AbstractRestClient;
import org.geoscheduler.android.rest.EventSynchronizer;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.android.tools.DBModel.EventCols;
import org.geoscheduler.model.Event;
import org.geoscheduler.model.Token;
import org.geoscheduler.model.Event.EventType;
import org.geoscheduler.model.dto.EventQueryDTO;
import org.json.JSONObject;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * Rest client able to synchronize local public events with ones on GS server according to current position.
 *
 * @author srakyi
 */
public class ServerEventSynchronizer extends AbstractRestClient implements EventSynchronizer {
	
	public static final String RES_PATH_EVENTS = "events";
	
	private Context ctx;
	
	public ServerEventSynchronizer(Context ctx) {
		super();
		
		this.ctx = ctx;
	}

	/**
	 * @see org.geoscheduler.android.rest.EventSynchronizer#storePrivateEvent(org.geoscheduler.model.Event)
	 */
	@Override
	public void storePrivateEvent(Event event) throws GSNotLoggedInException {
		Token token = GSContext.getToken();
		if (token == null) {
			throw new GSNotLoggedInException();
		} else if (token.getValidUntil().before(new Date())) {
			throw new GSNotLoggedInException("Token expired.");
		}
		
		throw new GSNotLoggedInException("This case isn't implemented.");
	}

	/**
	 * FIXME this is only naive implementation - it doesn't optimize transferred data amount at all (everything is deleted and newly loaded)
	 * 
	 * @see org.geoscheduler.android.rest.EventSynchronizer#updateTemporaryEvents(int, int)
	 */
	@Override
	public void updateTemporaryEvents(int lat, int lon) throws GSRestFailedException, GSRestReturnedErrorException, GSContextNotInitializedException {
		EventQueryDTO eqDTO = new EventQueryDTO();
		eqDTO.setLat(lat);
		eqDTO.setLon(lon);
		eqDTO.setTimeFrom(new Date());
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			cal.add(Calendar.MINUTE, 5);
		eqDTO.setTimeTo(cal.getTime());
		JSONObject eqJSON = marshall(eqDTO);
		
		List<Event> events = unmarshall(new Event(), restPostCallArray(ServerEventSynchronizer.RES_PATH_EVENTS, eqJSON));
		
		// TODO is this ok? (rewritten without testing)
		SQLiteDatabase db = DBHelper.openDB(this.ctx);
		db.delete(EventCols.TABLE_NAME, EventCols.EVENT_TYPE +" = ?", new String[]{""+EventType.TEMPORARY.ordinal()});
		
		for (Event e: events) {
			e.setEventTypeEnum(EventType.TEMPORARY);
			DBHelper.storeInst(db, e);
		}
	}
	
}
